package com.asj.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.asj.house.constant.RedisConstants;
import com.asj.house.entity.HouseRoom;
import com.asj.house.entity.HouseRoomDetail;
import com.asj.house.entity.HouseRoomRecommend;
import com.asj.house.mapper.HouseRoomRecommendMapper;
import com.asj.house.returns.RespCode;
import com.asj.house.returns.RespEntity;
import com.asj.house.service.HouseRoomDetailService;
import com.asj.house.service.HouseRoomRecommendService;
import com.asj.house.service.HouseRoomService;
import com.asj.house.utils.RedisUtil;
import com.asj.house.vo.TransferVO;
import com.asj.house.vo.result.TransferResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 房屋推荐表 服务实现类
 * </p>
 *
 * @author asj
 * @since 2021-03-16
 */
@Service
@Slf4j
public class HouseRoomRecommendServiceImpl extends ServiceImpl<HouseRoomRecommendMapper, HouseRoomRecommend> implements HouseRoomRecommendService {

    @Autowired
    private HouseRoomService houseRoomService;

    @Autowired
    private HouseRoomDetailService houseRoomDetailService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public RespEntity<TransferResult> getRecommendList() {
        String json = redisUtil.get(RedisConstants.key.RECOMMEND);
        if (StringUtils.isNotBlank(json)) {
            //使用缓存数据 获取左侧数据
            JSONArray jsonArray = JSONUtil.parseArray(json);
            List<TransferVO> transferVOList = JSONUtil.toList(jsonArray, TransferVO.class);

            //获取右侧数据 推荐房源信息
            List<String> rightData = getRightData();

            TransferResult transferResult = new TransferResult();
            transferResult.setLeftData(transferVOList);
            transferResult.setRightData(rightData);

            return new RespEntity<>(RespCode.SUCCESS, transferResult);
        }else {
            //新增缓存 并使用数据库数据
            return createRecommendCache();
        }

    }

    private RespEntity<TransferResult> createRecommendCache() {
        List<HouseRoom> houseRoomList = houseRoomService.list();
        if (Objects.isNull(houseRoomList) || CollectionUtil.isEmpty(houseRoomList)) {
            return new RespEntity<>(RespCode.SUCCESS);
        }

        //数据组装
        List<TransferVO> transferVOList = dataPackage(houseRoomList);
        TransferResult transferResult = new TransferResult();
        transferResult.setLeftData(transferVOList);

        //获取推荐房源数据
        List<String> roomIdList = getRightData();

        transferResult.setRightData(roomIdList);

        //设置缓存1分钟
        redisUtil.set(RedisConstants.key.RECOMMEND, JSONUtil.toJsonStr(transferVOList), 60);

        return new RespEntity<>(RespCode.SUCCESS, transferResult);
    }

    private List<String> getRightData() {
        List<HouseRoomRecommend> houseRoomRecommendList = baseMapper.selectList(null);

        if (Objects.isNull(houseRoomRecommendList) || CollectionUtil.isEmpty(houseRoomRecommendList)) {
            return new ArrayList<>();
        }

        return houseRoomRecommendList.stream()
                .map(v -> String.valueOf(v.getRoomId()))
                .collect(Collectors.toList());
    }

    private List<TransferVO> dataPackage(List<HouseRoom> houseRoomList) {
        List<TransferVO> transferVOList = Lists.newArrayList();

        for (HouseRoom houseRoom : houseRoomList) {
            //房源详细信息
            HouseRoomDetail houseRoomDetail = getHouseRoomDetail(houseRoom.getId());

            StringBuffer sb = new StringBuffer();
            sb.append(houseRoom.getName());
            sb.append("-");
            sb.append(getRoomType(houseRoom.getType()));
            sb.append("-");
            //校验是否是省份
            if (checkProvince(houseRoomDetail.getProvince())) {
                sb.append(houseRoomDetail.getProvince());
                sb.append("-");
            }
            sb.append(houseRoomDetail.getCity());
            sb.append("-");
            sb.append(houseRoomDetail.getAddress());

            TransferVO transferVO = TransferVO.builder()
                    .title(sb.toString())
                    .value(String.valueOf(houseRoom.getId()))
                    .build();

            transferVOList.add(transferVO);
        }

        return transferVOList;
    }

    private boolean checkProvince(String province) {
        boolean flag = true;
        switch (province) {
            case "北京市" : flag = false; break;
            case "天津市" : flag = false; break;
            case "上海市" : flag = false; break;
            case "重庆市" : flag = false;
        }
        return flag;
    }

    private HouseRoomDetail getHouseRoomDetail(Integer id) {
        QueryWrapper<HouseRoomDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HouseRoomDetail::getRoomId, id)
                .eq(HouseRoomDetail::getDeleted, 0);
        return houseRoomDetailService.getOne(queryWrapper);
    }

    public String getRoomType(Integer type) {
        String roomType = null;

        switch (type) {
            case 1 : roomType = "复式"; break;
            case 2 : roomType = "别墅"; break;
            case 3 : roomType = "园景房"; break;
            case 4 : roomType = "阁楼"; break;
            case 5 : roomType = "单元式"; break;
            case 6 : roomType = "公寓式";
        }

        return roomType;
    }


    @Override
    public RespEntity updateHouseRoomRecommend(String json, Integer index) {
        //index = 0 设置推荐; index = 1 取消推荐
        JSONArray jsonArray = JSONUtil.parseArray(json);
        List<TransferVO> transferVOList = JSONUtil.toList(jsonArray, TransferVO.class);

        //获取房源id集合
        List<String> roomIdList = transferVOList.stream()
                .map(TransferVO::getValue)
                .collect(Collectors.toList());

        //推荐设置
        switch (index) {
            case 0 : setHouseRecommend(roomIdList); break;
            case 1 : cancelHouseRecommend(roomIdList);
        }

        return new RespEntity(RespCode.SUCCESS);
    }

    /**
     * 取消推荐房源
     */
    private void cancelHouseRecommend(List<String> roomIdList) {
        for (String roomId : roomIdList) {
            QueryWrapper<HouseRoomRecommend> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(HouseRoomRecommend::getRoomId, roomId)
                    .eq(HouseRoomRecommend::getDeleted, 0);
            baseMapper.delete(queryWrapper);
        }
    }

    /**
     * 设置推荐房源
     */
    private void setHouseRecommend(List<String> roomIdList) {
        for (String roomId : roomIdList) {
            HouseRoomRecommend houseRoomRecommend = new HouseRoomRecommend();
            houseRoomRecommend.setRoomId(Integer.parseInt(roomId));
            houseRoomRecommend.setSeconds(3);
            baseMapper.insert(houseRoomRecommend);
        }
    }
}
